<template>
	<div class="cart">
		<h4>全部商品</h4>
		<div class="cart-main">
			<div class="cart-th">
				<div class="cart-th1">全部</div>
				<div class="cart-th2">商品</div>
				<div class="cart-th3">单价（元）</div>
				<div class="cart-th4">数量</div>
				<div class="cart-th5">小计（元）</div>
				<div class="cart-th6">操作</div>
			</div>
			<div class="cart-body">
				<ul class="cart-list" v-for="(cartInfo,index) in cartInfoList" :key="cartInfo.id">
					<li class="cart-list-con1">
						<input type="checkbox" name="chk_list" :checked="cartInfo.isChecked"
							@click="handleCheck(cartInfo.skuId,cartInfo.isChecked)">
					</li>
					<li class="cart-list-con2">
						<img :src="cartInfo.imgUrl">
						<div class="item-msg">{{cartInfo.skuName}}</div>
					</li>
					<li class="cart-list-con4">
						<span class="price">{{cartInfo.skuPrice}}.00</span>
					</li>
					<li class="cart-list-con5">
						<a @click="changeSkuNum('decrement',cartInfo)" class="mins">-</a>
						<input ref="skuNumInputs" @change="changeSkuNum('change',cartInfo,$event,index)" :value="cartInfo.skuNum" autocomplete="off" type="text" minnum="1" class="itxt">
						<a @click="changeSkuNum('increment',cartInfo)" class="plus">+</a>
					</li>
					<li class="cart-list-con6">
						<span class="sum">{{cartInfo.skuPrice * cartInfo.skuNum}}</span>
					</li>
					<li class="cart-list-con7">
						<a @click="handleDelete(cartInfo.skuId)" href="#none" class="sindelet">删除</a>
					</li>
				</ul>
			</div>
		</div>
		<div class="cart-tool" v-show="cartInfoList.length">
			<div class="select-all">
				<input class="chooseAll" type="checkbox" :checked="isAll" @click="handleCheckAll">
				<span>全选</span>
			</div>
			<div class="option">
				<a @click="handleBatchDelete">删除选中的商品</a>
			</div>
			<div class="money-box">
				<div class="chosed">已选择
					<span>{{checkedCount}}</span>件商品</div>
				<div class="sumprice">
					<em>总价（不含运费） ：</em>
					<i class="summoney">{{totalPrice}}</i>
				</div>
				<div class="sumbtn">
					<router-link class="sum-btn" to="/trade">结算</router-link>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import {mapGetters} from 'vuex'
	import throttle from 'lodash/throttle'
	import {
		reqCheckSkuInCart,
		reqCheckAllSkuInCart,
		reqDeleteSkuInCart,
		reqBatchDeleteSkuInCart,
		reqAddOrUpdateCart
	} from '@/api'
	import {skuNumReg} from '@/utils/reg'

	export default {
		name: 'Cart',
		methods: {
			//请求刷新购物车数据
			refreshCartInfoList(result) {
				//如果出错，提示一下
				if (result.code !== 200) alert(result.message)
				//重新获取购物车数据
				this.$store.dispatch('cart/getCartList')
			},
			//请求修改购物车中商品数量
			async updateSkuNum(skuId,disNum){
				// 通知服务器去加
				const result = await reqAddOrUpdateCart(skuId,disNum)
				//刷数据
				return this.refreshCartInfoList(result)
			},
			//勾选单个商品
			async handleCheck(skuId, isChecked) {
				//维护好isChecked
				isChecked = isChecked ? 0 : 1
				//联系服务器去切换状态
				const result = await reqCheckSkuInCart(skuId, isChecked)
				//刷数据
				this.refreshCartInfoList(result)
			},
			//全选
			async handleCheckAll(event) {
				//维护好isChecked
				const isChecked = event.target.checked ? 1 : 0
				//收集好skuIdList
				const skuIdList = this.cartInfoList.map(cartInfo => cartInfo.skuId)
				//联系服务器修改
				const result = await reqCheckAllSkuInCart(skuIdList, isChecked)
				//刷数据
				this.refreshCartInfoList(result)
			},
			//删除单个
			async handleDelete(skuId) {
				if (confirm('确定删除吗？')) {
					//发请求去删除
					const result = await reqDeleteSkuInCart(skuId)
					//刷数据
					this.refreshCartInfoList(result)
				}
			},
			//批量删除
			async handleBatchDelete() {
				//准备好一个存储删除商品的数组
				let skuIdList = []
				//收集所有选中商品的skuId
				this.cartInfoList.forEach(cartInfo => {
					if (cartInfo.isChecked) skuIdList.push(cartInfo.skuId)
				});
				//发请求进行批量删除
				const result = await reqBatchDeleteSkuInCart(skuIdList)
				//刷数据
				this.refreshCartInfoList(result)
			},
			//修改商品数量
			changeSkuNum:throttle(function (type,cartInfo,event,index){
				//获取当前操作商品的编号、数量
				const {skuId,skuNum} = cartInfo
				//根据不同的修改类型，执行不同的逻辑
				switch (type) {
					case 'increment':
						//校验极限值
						if(skuNum + 1 > 200) return alert('最大数量为200！')
						//调用updateSkuNum去联系服务器，真正加
						return this.updateSkuNum(skuId,1)

					case 'decrement':
						if(skuNum - 1 < 1) return alert('最小数量为1！')
						//调用updateSkuNum去联系服务器，真正加
						return this.updateSkuNum(skuId,-1)

					case 'change':
						//获取用户的输入
						const inputNum = event.target.value
						//校验数据
						if(skuNumReg.test(inputNum)){
							//调用updateSkuNum去联系服务器，真正加
							this.updateSkuNum(skuId,inputNum-skuNum)
						}
						else if(inputNum > 200){
							//重置页面上的输入框的值
							this.$refs.skuNumInputs[index].value = 200
							//调用updateSkuNum去联系服务器，真正加
							this.updateSkuNum(skuId,200-skuNum)
						}
						else{
							//将当前操作的商品的数量变为之前的值
							this.$refs.skuNumInputs[index].value = skuNum
						}
				}
			},500,{trailing:false})
		},
		computed: {
			...mapGetters('cart', ['cartInfoList']),
			//是否全选
			isAll() {
				return this.cartInfoList.every((cartInfo) => {
					return cartInfo.isChecked === 1
				})
			},
			//已选择的数量
			checkedCount() {
				return this.cartInfoList.reduce((pre, cartInfo) => {
					return pre + (cartInfo.isChecked ? cartInfo.skuNum : 0)
				}, 0)
			},
			//总价格
			totalPrice() {
				return this.cartInfoList.reduce((pre, cartInfo) => {
					return pre + (cartInfo.isChecked ? cartInfo.skuNum * cartInfo.skuPrice : 0)
				}, 0)
			}
		},
		mounted() {
			this.$store.dispatch('cart/getCartList')
		},
	}
</script>

<style lang="less" scoped>
	.cart {
		width: 1200px;
		margin: 0 auto;

		h4 {
			margin: 9px 0;
			font-size: 14px;
			line-height: 21px;
		}

		.cart-main {
			.cart-th {
				background: #f5f5f5;
				border: 1px solid #ddd;
				padding: 10px;
				overflow: hidden;

				&>div {
					float: left;
				}

				.cart-th1 {
					width: 25%;

					input {
						vertical-align: middle;
					}

					span {
						vertical-align: middle;
					}
				}

				.cart-th2 {
					width: 25%;
				}

				.cart-th3,
				.cart-th4,
				.cart-th5,
				.cart-th6 {
					width: 12.5%;
				}
			}

			.cart-body {
				margin: 15px 0;
				border: 1px solid #ddd;

				.cart-list {
					padding: 10px;
					border-bottom: 1px solid #ddd;
					overflow: hidden;

					&>li {
						float: left;
					}

					.cart-list-con1 {
						width: 15%;
					}

					.cart-list-con2 {
						width: 35%;

						img {
							width: 82px;
							height: 82px;
							float: left;
						}

						.item-msg {
							float: left;
							width: 150px;
							margin: 0 10px;
							line-height: 18px;
						}
					}

					.cart-list-con4 {
						width: 10%;
					}

					.cart-list-con5 {
						width: 17%;

						.mins {
							border: 1px solid #ddd;
							border-right: 0;
							float: left;
							color: #666;
							width: 6px;
							text-align: center;
							padding: 8px;
						}

						input {
							border: 1px solid #ddd;
							width: 40px;
							height: 33px;
							float: left;
							text-align: center;
							font-size: 14px;
						}

						.plus {
							border: 1px solid #ddd;
							border-left: 0;
							float: left;
							color: #666;
							width: 6px;
							text-align: center;
							padding: 8px;
						}
					}

					.cart-list-con6 {
						width: 10%;

						.sum {
							font-size: 16px;
						}
					}

					.cart-list-con7 {
						width: 13%;

						a {
							color: #666;
						}
					}
				}
			}
		}

		.cart-tool {
			overflow: hidden;
			border: 1px solid #ddd;

			.select-all {
				padding: 10px;
				overflow: hidden;
				float: left;

				span {
					vertical-align: middle;
				}

				input {
					vertical-align: middle;
				}
			}

			.option {
				padding: 10px;
				overflow: hidden;
				float: left;

				a {
					float: left;
					padding: 0 10px;
					color: #666;
				}
			}

			.money-box {
				float: right;

				.chosed {
					line-height: 26px;
					float: left;
					padding: 0 10px;
				}

				.sumprice {
					width: 200px;
					line-height: 22px;
					float: left;
					padding: 0 10px;

					.summoney {
						color: #c81623;
						font-size: 16px;
					}
				}


				.sumbtn {
					float: right;

					a {
						display: block;
						position: relative;
						width: 96px;
						height: 52px;
						line-height: 52px;
						color: #fff;
						text-align: center;
						font-size: 18px;
						font-family: "Microsoft YaHei";
						background: #e1251b;
						overflow: hidden;
					}
				}
			}
		}
	}
</style>